package per.mnxc.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.DigestUtils;
import per.mnxc.common.R;
import per.mnxc.dto.UserDto;
import per.mnxc.pojo.User;
import per.mnxc.mapper.UserMapper;
import per.mnxc.service.IUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.stereotype.Service;

import javax.servlet.http.HttpServletRequest;
import java.nio.charset.StandardCharsets;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author mnxc
 * @since 2022-11-26
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {
    @Autowired
    UserMapper userMapper;

    @Override
    public R<User> login(HttpServletRequest request,User user) {
        //1.查询用户
        LambdaQueryWrapper<User> lqw = new LambdaQueryWrapper<>();
        lqw.eq(User::getUserPhone,user.getUserPhone());
        User one = userMapper.selectOne(lqw);
        if(one == null)return R.error("用户名或密码错误");
        //2.验证密码
        String password = DigestUtils.md5DigestAsHex(user.getUserPWD().getBytes(StandardCharsets.UTF_8));
        if(!one.getUserPWD().equals(password)) return R.error("用户名或密码错误");
        //3.记录用户登录信息
        request.getSession().setAttribute("userId",one.getUserid());

        return R.success(one);
    }

    @Override
    public R<String> logout(HttpServletRequest request) {
        request.getSession().removeAttribute("userId");
    return R.success("退出成功");
    }
}
